package com.willian.andrappfw.network;

import android.text.TextUtils;

import com.google.gson.GsonBuilder;
import com.willian.andrappfw.AppBuildConfig;
import com.willian.andrappfw.network.interceptor.LogInterceptor;
import com.willian.andrappfw.utils.WPreferenceManager;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class WApiRetrofit {
    private static WApiRetrofit instance = new WApiRetrofit();
    private Retrofit mRetrofit;

    public static WRequests getInstance() {
        return instance.mRetrofit.create(WRequests.class);
    }

    private WApiRetrofit() {
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new LogInterceptor())
                .addInterceptor(chain -> {
                    Request request;
                    if (!TextUtils.isEmpty(WPreferenceManager.getToken())) {
                        request = chain.request()
                                .newBuilder()
                                .addHeader("Authorization", WPreferenceManager.getToken())
                                .build();
                    } else {
                        request = chain.request();
                    }
                    return chain.proceed(request);
                })
                .build();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(AppBuildConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(mOkHttpClient)
                .build();
    }
}
